package com.springboot.personblogsystem.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.springboot.personblogsystem.common.Result;
import com.springboot.personblogsystem.common.req.AddBlogParam;
import com.springboot.personblogsystem.common.req.UpdateBlogParam;
import com.springboot.personblogsystem.common.resp.ArticleResponse;
import com.springboot.personblogsystem.mapper.BlogMapper;
import com.springboot.personblogsystem.model.Article;
import com.springboot.personblogsystem.model.User;
import com.springboot.personblogsystem.service.BlogService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.springboot.personblogsystem.common.Constants.USERINFO;

/**
 * Created with IntelliJ IDEA.
 * Description :
 * User: jiume
 * Date: 2025-05-14
 * Time: 17:28
 */
@Slf4j
@Service
public class BlogServiceImp implements BlogService {

    @Resource
    private BlogMapper blogMapper;

    @Override
    public Result<Long> getBlogCount(HttpServletRequest request) {
        // 由于拦截器的存在，当走到这里时，用户肯定是登录了，因此可以直接获取个人信息
        User user = (User) request.getSession(false).getAttribute(USERINFO);
        Long id = user.getId();
        // 在文章表中根据user_id来查询文章数量
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", id).eq("status", 0);
        Long blogCount = blogMapper.selectCount(queryWrapper);
        log.info("[getBlogCount]: 获取 " + user.getUserName() + "的博客数量为: " + blogCount);
        return Result.success(blogCount);
    }

    @Override
    public Result<Long> getBlogSort(HttpServletRequest request) {
        // 1、获取userId
        User user = (User) request.getSession(false).getAttribute(USERINFO);
        Long id = user.getId();
        // 2、获取Id对应的文章分类的数量
        // SQL: select count(distinct article_sort) from article where user_id = 1;
        // 这里无法直接通过条件构造器来实现，因此这里我们可以使用自定义SQL
        Long articleSort = blogMapper.queryArticleSortByUserId(id);
        log.info("[getBlogSort]: 获取" + user.getUserName() + "的文章分类数量: " + articleSort);
        return Result.success(articleSort);
    }

    @Override
    public Result<List<ArticleResponse>> getBlog(HttpServletRequest request) {
        // 1、获取用户Id
        User user = (User) request.getSession(false).getAttribute(USERINFO);
        Long id = user.getId();
        // 2、获取该用户Id的所有文章（按照更新时间降序排序）
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", id)
                .eq("status", 0)
                .orderByDesc("update_time");
        List<Article> articleList = blogMapper.selectList(queryWrapper);
        if (articleList.size() == 0) {
            log.info("[getBlog]: 获取 " +user.getUserName()+" 的文章失败, 数量为: 0");
            return Result.success(new ArrayList<>());
        }
        // 3、把 article对象 转换为 articleResponse对象
        // 1)把文章长度大于50的，简略显示
        // 2)把时间格式转换为正常的时间显示（年月日时分秒）
        List<ArticleResponse> articleResponses = new ArrayList<>();
        for (Article article : articleList) {
            if (article.getContent().length() > 50) {
                article.setContent(article.getContent().substring(0, 50));
            }
            // 定义格式化器
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 格式化输出
            String formatted = sdf.format(article.getCreateTime());

            // 对象转换
            ArticleResponse response = new ArticleResponse();
            response.setId(article.getId());
            response.setArticleName(article.getArticleName());
            response.setContent(article.getContent());
            response.setUserId(article.getUserId());
            response.setSort(article.getSort());
            response.setStatus(article.getStatus());
            response.setCreateTime(article.getCreateTime());
            response.setCreateTimeFormat(formatted);
            response.setUpdateTime(article.getUpdateTime());

            articleResponses.add(response);
        }
        log.info("[getBlog]: 获取 " +user.getUserName()+" 的文章成功, 数量为: "+articleList.size());
        return Result.success(articleResponses);
    }

    @Override
    public Result<ArticleResponse> getBlogDetail(Long articleId) {
        // 1、判断参数是否合法
        if (articleId == null || articleId <= 0) {
            log.info("[getBlogDetail]: 参数不合法");
            return Result.error("参数不合法", null);
        }
        // 2、查询数据库中 文章信息
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", articleId).eq("status", 0);
        Article article = blogMapper.selectById(articleId);
        if (article == null) {
            log.info("[getBlogDetail]: 获取文章id为 " +articleId+" 的文章失败, 不存在该文章信息");
            return Result.error("不存在该文章信息",null);
        }
        // 3、将 article对象 转换为 articleResponse对象

        // 定义格式化器
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 格式化输出
        String formatted = sdf.format(article.getCreateTime());

        // 对象转换
        ArticleResponse response = new ArticleResponse();
        response.setId(article.getId());
        response.setArticleName(article.getArticleName());
        response.setContent(article.getContent());
        response.setUserId(article.getUserId());
        response.setSort(article.getSort());
        response.setStatus(article.getStatus());
        response.setCreateTime(article.getCreateTime());
        response.setCreateTimeFormat(formatted);
        response.setUpdateTime(article.getUpdateTime());

        return Result.success(response);
    }

    @Override
    public Result<Boolean> addBlog(AddBlogParam addBlogParam, HttpServletRequest request) {
        // 1、校验参数是否合法
        if (addBlogParam == null
                || !StringUtils.hasText(addBlogParam.getTitle())
                || !StringUtils.hasText(addBlogParam.getContent())) {
            log.info("[addBlog]: 参数不合法");
            return Result.error("参数不合法", false);
        }
        // 2、往数据库中插入文章信息
        Article article = new Article();
        article.setArticleName(addBlogParam.getTitle());
        article.setContent(addBlogParam.getContent());
        Long userId = ((User)request.getSession(false).getAttribute(USERINFO)).getId();
        article.setUserId(userId);
        article.setSort("默认分类");
        int result = blogMapper.insert(article);
        if (result != 1) {
            log.info("[addBlog]: 新增失败: "+addBlogParam.getTitle());
            return Result.error("新增失败", false);
        }
        log.info("[addBlog]: 新增成功: "+addBlogParam.getTitle());
        return Result.success(true);
    }

    @Override
    public Result<Boolean> updateBlog(UpdateBlogParam updateBlogParam) {
        // 1、校验参数
        if (updateBlogParam == null
                || updateBlogParam.getArticleId() == null
                || updateBlogParam.getArticleId() <= 0
                || !StringUtils.hasText(updateBlogParam.getTitle())
                || !StringUtils.hasText(updateBlogParam.getContent())) {
            log.info("[updateBlog]: 参数不合法");
            return Result.error("参数不合法");
        }
        // 更新数据库信息
        UpdateWrapper<Article> updateWrapper = new UpdateWrapper<>();
        //update article set article_name = '个人介绍—李四' where id = 5;
        updateWrapper.set("article_name", updateBlogParam.getTitle())
                .set("article_content", updateBlogParam.getContent())
                .in("id", updateBlogParam.getArticleId());
        int result = blogMapper.update(updateWrapper);
        if (result != 1) {
            log.info("[updateBlog]: 更新失败: "+updateBlogParam.getArticleId());
            return Result.error("更新失败", false);
        }
        log.info("[updateBlog]: 更新成功: "+updateBlogParam.getArticleId());
        return Result.success(true);
    }

    @Override
    public Result<Boolean> deleteBlog(Long articleId) {
        if (articleId == null || articleId <= 0) {
            log.info("[deleteBlog]: 参数不合法");
            return Result.error("参数不合法", false);
        }
        // 删除数据库中文章
        UpdateWrapper<Article> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("status", 1).in("id", articleId);
        int result = blogMapper.update(updateWrapper);
        if (result != 1) {
            log.info("[deleteBlog]: 删除失败: "+articleId);
            return Result.error("删除失败", false);
        }
        log.info("[deleteBlog]: 删除成功: "+articleId);
        return Result.error("删除成功", true);
    }
}
